import router from '@/router';
import axios from 'axios'
import qsString from 'querystring'


let baseUrl = '/api'

axios.interceptors.request.use(req => {
    // console.log(req, '请求');
    if (req.url != '/api/userlogin') {
        req.headers.authorization = sessionStorage.getItem('userinfo') ? JSON.parse(sessionStorage.getItem('userinfo')).token : null
    }
    return req
})

axios.interceptors.response.use(res => {
    if (res.data.msg == '请设置请求头,并携带验证字符串') {
        alert(res.data.msg)
        router.push('/login')
    }
    if (res.data.msg == '登录已过期或访问权限受限') {
        alert(res.data.msg)
        router.push('/login')
    }
    return res.data
})


export const get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        axios.get(baseUrl + url, { params })
            .then(res => {
                resolve(res)
            }).catch(err => {
                reject(err)
            })
    })
}

export const post = (url, params = {}, isFile = false) => {
    let data = {}
    if (isFile) {
        data = new FormData()
        for (let i in params) {
            data.append(i, params[i])
        }
    } else {
        data = qsString.stringify(params)
    }
    return new Promise((resolve, reject) => {
        axios.post(baseUrl + url, data)
            .then(res => {
                resolve(res)
            }).catch(err => {
                reject(err)
            })
    })
}